/**
 * @description 该文件使用axios的方式提供request方法，实际请求时，使用的是uni.request
 * 
*/

import axios  from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'


import { Session } from './storage';
// @ts-ignore
import * as CryptoJS from 'crypto-js';
import { useMessageBox } from '../hooks/message';

export const baseUrl = 'http://116.62.172.200:9999'

function encryption(src: string, keyWord: string) {
    const key = CryptoJS.enc.Utf8.parse(keyWord);
    // 加密
    var encrypted = CryptoJS.AES.encrypt(src, key, {
        iv: key,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.NoPadding,
    });
    return encrypted.toString();
}

function decryption(src: string, keyWord: string) {
    const key = CryptoJS.enc.Utf8.parse(keyWord);
    // 解密逻辑
    var decryptd = CryptoJS.AES.decrypt(src, key, {
        iv: key,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.NoPadding,
    });

    return decryptd.toString(CryptoJS.enc.Utf8);
}

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

const service:AxiosInstance = axios.create({
	baseURL: "/apiRequest", 
	timeout: 6000,
})

// 请求拦截
service.interceptors.request.use((config:InternalAxiosRequestConfig) => {
    const token = Session.getToken();
    if (token && !config.headers?.skipToken) {
      config.headers![CommonHeaderEnum.AUTHORIZATION] = `Bearer ${token}`;
    }
    config.headers![CommonHeaderEnum.CLIENT] = 'hss';
    if (config.headers![CommonHeaderEnum.ENC_FLAG]) {
      
      const enc = encryption(JSON.stringify(config.data), import.meta.env.VITE_PWD_ENC_KEY);
      config.data = {
        encryption: enc,
      };
    }
		return config;
	},
	error => {
		return Promise.reject(error);
	});

const handleResponse = (response: AxiosResponse<any>) => {
	if (response.data.code === 1) {
		throw response.data;
	}

	// 针对密文返回解密
	if (response.data.encryption) {
		const originData = JSON.parse(decryption(response.data.encryption, import.meta.env.VITE_PWD_ENC_KEY));
		response.data = originData;
		return response.data;
	}

	return response.data;
};

service.interceptors.response.use(handleResponse, (error) => {
	const status = Number(error.response.status) || 200;
	if (status === 424) {
		useMessageBox()
			.confirm('令牌状态已过期，请点击重新登录')
			.then(() => {
				Session.clear(); // 清除浏览器全部临时缓存
				uni.navigateTo({
				  url:'/pages/login/index'
				})
				return;
			});
	}
	return Promise.reject(error.response.data);
});



// 常用header
export enum CommonHeaderEnum {
	'TENANT_ID' = 'TENANT-ID',
	'ENC_FLAG' = 'Enc-Flag',
	'AUTHORIZATION' = 'Authorization',
	'CLIENT' = 'hss-client-id',
}
export default service
